//
//  AccountDetailsViewController.m
//  UcarTest
//
//  Created by 陈曦 on 16/3/13.
//  Copyright © 2016年 chenxi. All rights reserved.
//

#import "AccountDetailsViewController.h"
#import "Define.h"
#import "AFNetworking.h"
#import "NetRequestGroup.h"
#import "Access_token.h"
#import "MBProgressHUD.h"
#import "AccountDetailModel.h"
#import "AccountDetailTableViewCell.h"

@interface AccountDetailsViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *accountDetailTableView;

@property (nonatomic, strong) NSMutableArray *listArray;//列表返回值集合

@end

@implementation AccountDetailsViewController

static NSString *accountAeidentifier = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];

    //导航条
    self.navigationController.navigationBarHidden = NO;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"账户明细";
    self.navigationItem.titleView = titleLabel;
    self.navigationController.navigationBar.barTintColor = mainColor;
    self.view.backgroundColor = backgroundMainColor;
    

    
    //重定义返回键
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(0, 0, 22, 22);
    [back setImage:[UIImage imageNamed:@"iconfont-fanhui-white"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backTpMainView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backBar;


    //网络请求
    self.nowPage = 0;
    [self NetworkRequests];
    
    
}






#pragma mark 网络请求
- (void) NetworkRequests{
    
    self.listArray = [NSMutableArray array];

    //初始化进度框，置于当前的View当中
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.label.text = @"正在加载";
    [HUD showAnimated:YES];//HUD开始
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    Access_token *useAccess = [Access_token shareInstance];
    
    NSString *page = [NSString stringWithFormat:@"%ld", self.nowPage];
    
    //传入的参数
    NSDictionary *para = @{
                           @"type" : @"1",
                           @"access_token" : useAccess.access_token,
                           @"page" : page
                           };
    //你的接口地址
    NSString *url = [NSString stringWithFormat:@"%@%@", kRealmName, kNetMoneyAccount];
    //发送请求
    [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [HUD hideAnimated:YES];
        
        NSDictionary *dic = responseObject;
        
        NSString *status = dic[@"status"];
                
        NSDictionary *info = dic[@"info"];
        
        NSString *allPageStr = info[@"page_count"];
        
        self.allPage = [allPageStr intValue];
        
        for (NSDictionary *diccc in info[@"list"]) {
            
            AccountDetailModel *accountModel = [[AccountDetailModel alloc] init];
            [accountModel setValuesForKeysWithDictionary:diccc];
            
            [self.listArray addObject:accountModel];
            
        }
        
            [self.accountDetailTableView  reloadData];

        [self setupTableView];

        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [HUD hideAnimated:YES];
        
        //初始化提示框；
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
        
    }];
    
    
}

//封装列表
- (void) setupTableView {
    
    self.accountDetailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 80, kScreenWidth, self.listArray.count * 72)];
    [self.view addSubview:self.accountDetailTableView];
    self.accountDetailTableView.dataSource = self;
    self.accountDetailTableView.delegate = self;
    
    [self.accountDetailTableView registerClass:[AccountDetailTableViewCell class] forCellReuseIdentifier:accountAeidentifier];
    
    [self headerWithRefreshing];
    
    [self footerWithRefreshing];


}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.listArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 72;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AccountDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:accountAeidentifier forIndexPath:indexPath];
    cell.model = self.listArray[indexPath.row];

    return cell;
    
}


#pragma mark 下拉刷新
- (void)headerWithRefreshing{
    
    
    self.accountDetailTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if(self.nowPage > 0) {
            
            //当页数大于0 上拉刷新为 -1
            self.nowPage = self.nowPage - 1;
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.accountDetailTableView reloadData];
                
                //删除当前页
                [self.accountDetailTableView removeFromSuperview];
                
                // 结束刷新
                [self.accountDetailTableView.mj_header endRefreshing];
                
                //重新载入列表
                [self setupTableView];
                
            });
        } else if (self.nowPage <= 0) {
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.accountDetailTableView reloadData];
                
                //删除当前页
                [self.accountDetailTableView removeFromSuperview];
                
                // 结束刷新
                [self.accountDetailTableView.mj_header endRefreshing];
                
                //重新载入列表
                [self setupTableView];
                
                
            });
            
        }
        
    }];
}

#pragma mark 上拉刷新
- (void) footerWithRefreshing{
    
    
    // 上拉刷新
    self.accountDetailTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (self.nowPage < self.allPage - 1) {
            
            //上拉为当前页数加1
            self.nowPage = self.nowPage + 1;
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.accountDetailTableView reloadData];
                
                //删除当前页
                [self.accountDetailTableView removeFromSuperview];
                
                // 结束刷新
                [self.accountDetailTableView.mj_header endRefreshing];
                
                //重新载入列表
                [self setupTableView];
                
            });
            
        } else if (self.nowPage >= self.allPage - 1){
            
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.accountDetailTableView reloadData];
                
                //删除当前页
                [self.accountDetailTableView removeFromSuperview];
                
                // 结束刷新
                [self.accountDetailTableView.mj_header endRefreshing];
                
                //重新载入列表
                [self setupTableView];
                
                
            });
            
            
        }
        
    }];
    
}









//返回上一页
- (void)backTpMainView{
    
    
    [self.navigationController popViewControllerAnimated:nil];
    
    
}

@end
